package com.jsyh.maidu.fragment;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.jsyh.maidu.R;
import com.jsyh.maidu.activity.ArticleActivity;
import com.jsyh.maidu.activity.SearchActivity;
import com.jsyh.maidu.activity.ShoppingCartActivity;
import com.jsyh.maidu.adapter.category.CategoryTopAdapter;
import com.jsyh.maidu.http.OkHttpClientManager;
import com.jsyh.maidu.model.CategoryInfo;
import com.jsyh.maidu.model.CategoryInfoModel;
import com.jsyh.maidu.presenter.CategoryPresenter;
import com.jsyh.maidu.qrzxing.CaptureActivity;
import com.jsyh.maidu.views.CategoryView;
import com.umeng.socialize.facebook.controller.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * MD 历史的 鬼东西，cccccc
 * 分类
 */
public class CategoryFragment extends Fragment implements
        CategoryView,
        AdapterView.OnItemClickListener,
        View.OnClickListener {

    private CategoryPresenter mPresenter;

    private FullScreanDialogFragment mSearchDialog;

    private LinearLayout mMainContent;

    private ViewStub mNetworStub;
    private View mNetworkErrorLayout;
    private Button mReloadRequest;            //网络错误k

    //--------------- 一级列表 ----------------------
    private ListView mOneListView;
    private CategoryTopAdapter mOneAdapter;
    private List<CategoryInfo> mOneData;

    //--------------- 二级列表 ----------------------
    private FragmentManager mFragmentManager;
    private FragmentTransaction mft;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFragmentManager = getChildFragmentManager();
        mPresenter = new CategoryPresenter(this);

    }

    private View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.category_fragment, container, false);
            mNetworStub = (ViewStub) rootView.findViewById(R.id.vsNetworkError);
            mMainContent = (LinearLayout) rootView.findViewById(R.id.mainContents);
            initOneCategory(rootView);
            mPresenter.loadCategoryByType(getActivity(), CategoryPresenter.one_level, null);
            rootView.findViewById(R.id.txtMessage).setOnClickListener(this);
            rootView.findViewById(R.id.lineLaySearch).setOnClickListener(this);
            rootView.findViewById(R.id.txtGoCar).setOnClickListener(this);
        }
        return rootView;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btnReloadNetwork:        //重新加载网络
                mPresenter.loadCategoryByType(getContext(), CategoryPresenter.one_level, null);
                break;
            case R.id.txtMessage:
                Intent intent = new Intent(getActivity(), ArticleActivity.class);
                startActivity(intent);
                break;
            case R.id.lineLaySearch:
                Intent search = new Intent(getActivity(), SearchActivity.class);
                startActivity(search);
                break;
            case R.id.txtGoCar:
                Intent carIntent =new Intent(getActivity(),ShoppingCartActivity.class);
                startActivity(carIntent);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent itCapture = new Intent(getActivity(), CaptureActivity.class);
                startActivity(itCapture);
            } else {
                ToastUtil.showToast(getActivity(), "权限被拒绝，相关功能无法使用！");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 初始化一级列表
     *
     * @param v
     */
    private void initOneCategory(View v) {
        mOneListView = (ListView) v.findViewById(R.id.lvOneLevel);
        mOneListView.setOnItemClickListener(this);

        mOneAdapter = new CategoryTopAdapter(getActivity(), R.layout.category_one_level_item);
        mOneListView.setAdapter(mOneAdapter);

    }

    /**
     * 一级 分类回调
     *
     * @param data
     */
    @Override
    public void onOneLevelData(CategoryInfoModel data, @Nullable Exception e) {
        if (e != null) {
            switchLayout();
            return;
        }
        if (data == null) return;
        if (mNetworkErrorLayout != null) {
            mNetworkErrorLayout.setVisibility(View.GONE);
        }
        mMainContent.setVisibility(View.VISIBLE);
        if (mOneData == null) {
            mOneData = new ArrayList<>();
        }
        mOneData.clear();
        mOneAdapter.clear();
        data.getData().getClassify().get(currPosition).setChecked(true); //第一个默认选中
        mOneData.addAll(data.getData().getClassify());
        mOneAdapter.addAll(this.mOneData);
        checkCacheWithLoad(currPosition, Integer.valueOf(data.getData().getClassify().get(currPosition).getClassify_id()));

    }

    /**
     * 二级分类回调
     *
     * @param data
     */
    @Override
    public void onTwoLevelData(CategoryInfoModel data, @Nullable Exception e) {
        if (e != null) {
            switchLayout();
            return;
        }
        if (mNetworkErrorLayout != null) {
            mNetworkErrorLayout.setVisibility(View.GONE);
        }
        mMainContent.setVisibility(View.VISIBLE);
        if (data.getData() != null) {
            mFragmentManager.beginTransaction()
                    .replace(R.id.contents, CategorySubFragment.newInstance(data))
                    .commitAllowingStateLoss();
        }
    }

    public void switchLayout() {
        if (mNetworkErrorLayout == null) {
            mNetworkErrorLayout = mNetworStub.inflate();
            mReloadRequest = (Button) mNetworkErrorLayout.findViewById(R.id.btnReloadNetwork);
            mReloadRequest.setOnClickListener(this);
        } else {
            mNetworkErrorLayout.setVisibility(View.VISIBLE);
        }
        mMainContent.setVisibility(View.GONE);
    }

    private int currPosition;
    private TextView currItemView;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        OkHttpClientManager.cancelTag(getContext(), "category" + CategoryPresenter.one_level);
        OkHttpClientManager.cancelTag(getContext(), mPresenter.getTag());
    }

    /**
     * 一级item点击事件
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (currPosition == position) {
            return;
        }
        mOneData.get(currPosition).setChecked(false);
        mOneData.get(position).setChecked(true);
        currPosition = position;
        mOneAdapter.notifyDataSetChanged();
        if (android.os.Build.VERSION.SDK_INT >= 11) {
            mOneListView.smoothScrollToPositionFromTop(position, 0);
        } else {
            mOneListView.setSelectionFromTop(position, 0);
        }

        mPresenter.loadCategoryByType(getContext(), CategoryPresenter.two_level, Integer.valueOf(mOneData.get(currPosition).getClassify_id()));
    }

    /**
     * 判断缓存中是否已经存在
     */
    private void checkCacheWithLoad(int key, int id) {
        //判断个 JJ 啊，我已经删了。。。。。
        mPresenter.loadCategoryByType(getActivity(), CategoryPresenter.two_level, id);
    }


}
